var http = require('./http.js')
var Constant = require('./constant.js')
import Wechat from './wechat.js'

import i18n from '../main.js'
import MD5 from './md5.js'

export default {

	/**
	 * 订单支付
	 * @param {Number} payType 支付类型;见util/constant.js
	 * @param {Strint} orderNumbers 订单编号
	 * @param {Boolean} isPurePoints 是否纯积分订单(积分+钱订单与普通订单一致)
	 * @param {Boolean} dvyType // 配送类型 1:快递 2:自提 3：无需快递 4:同城配送
	 * @param {Number/String} vipId 要购买的会员等级id
	 * @param {Number/String} balance 余额充值
	 * @param {Number/String} orderType 订单类型 1团购 2秒杀
	 * @param {Number/String} token 
	 */
	// uni.getStorageSync('token')
	toOrderPay(payType, orderNumbers, isPurePoints, dvyType, vipId, balance, orderType, token) {
		debugger
		console.log(payType, orderNumbers, isPurePoints, dvyType, vipId, balance, orderType, token)
		uni.showLoading({
			mask: true
		})
		const balanceId = balance ? balance.balanceId : null
		const customRechargeAmount = balance ? balance.customRechargeAmount : null
		let redirectUrl = '/packageUser/pages/myWallet/myWallet'
		let tokenNum = uni.getStorageSync('token')
		// #ifdef H5
		var {
			protocol,
			host
		} = window.location
		if (balanceId) {
			redirectUrl = `${protocol}//${host}` + '/packageUser/pages/myWallet/myWallet'
		} else if (vipId) {
			redirectUrl = `${protocol}//${host}` + '/packageMemberIntegral/pages/buyVip/buyVip'
		} else {
			redirectUrl = `${protocol}//${host}` + '/packageUser/pages/orderList/orderList?sts=0'
		}
		// #endif
		// 常规订单请求参数
		const commonOrderData = {
			payType: payType,
			orderNumbers: orderNumbers,
			returnUrl: redirectUrl,
			// token:'bearerf643cab0-2c64-468a-a7e7-0c86110ba160',
			token: tokenNum
		}
		console.log(commonOrderData)
		// 购买vip订单请求参数
		const buyVipOrderData = {
			id: vipId,
			scene: '',
			payType: payType
		}
		// 充值余额
		const rechargeBalanceData = {
			payType: payType,
			returnUrl: redirectUrl,
			id: balanceId,
			customRechargeAmount: customRechargeAmount,
			scene: ''

		}
		const params = {
			url: vipId ? "/p/level/payLevel" : balanceId ? '/p/balance/pay' : "/p/order/pay",
			method: "POST",
			data: vipId ? buyVipOrderData : balanceId ? rechargeBalanceData : commonOrderData,
			callBack: (res) => {
				debugger
				console.log(res)
				let _this = this
				uni.hideLoading()
				// 积分订单: 纯积分 isPurePoints=1 或者 纯积分支付
				if (isPurePoints == 1 || payType == 0) {
					uni.redirectTo({
						url: '/packageProduct/pages/pay-result/pay-result?sts=1&orderNumbers=' +
							orderNumbers +
							'&orderType=' + orderType
					});
				} else {
					// 微信h5支付
					if (Constant.PayType.WECHATPAY_H5 == payType) {
						var url = encodeURIComponent(redirectUrl)
						window.location.href = res + "&redirect_url=" + url
						return;
					}
					// 微信公众号支付
					else if (Constant.PayType.WECHATPAY_MP == payType) {
						Wechat.callWexinPay(res, () => {
							//支付成功
							_this.routeToAfterPay(true, dvyType, vipId, balanceId, orderNumbers,
								payType)
						}, () => {
							// 支付失败
							_this.routeToAfterPay(false, dvyType, vipId, balanceId, orderNumbers,
								payType)
						})
					}
					//支付宝支付
					else if (Constant.PayType.ALIPAY_H5 == payType) {
						this.$nextTick(() => {
							document.forms[0].submit()
						})
					}
					// 余额支付
					else if (Constant.PayType.BALANCEPAY == payType && !vipId) {
						// type 1支付成功 2用户信息异常 3余额不足
						if (res.type == 1) {
							_this.routeToAfterPay(true, dvyType, vipId, balanceId, orderNumbers, payType)
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
								duration: 1500
							})
						}
					}
					// PayPal支付
					else if (Constant.PayType.PAYPAL == payType) {
						// console.log("paypal支付")
						// console.log("res", res)
						window.location.href = res
					}
					// 余额购买会员
					else if (Constant.PayType.BALANCEPAY == payType && vipId) {
						// type 1支付成功 2用户信息异常 3余额不足
						if (res.type == 1) {
							uni.showToast({
								title: i18n.t('index.purchaseSuccessful'),
								icon: 'none',
								duration: 1000
							})
							setTimeout(() => {
								uni.redirectTo({
									url: '/packageMemberIntegral/pages/buyVip/buyVip'
								})
							}, 1000)
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
								duration: 1500
							})
						}
					} else {
						// #ifdef APP-PLUS
						// var wxAppPayInfo = {}
						if (payType == Constant.PayType.WECHATPAY_APP) {

							var wxAppPayInfo = {
								"appid": res.appid,
								"partnerid": res.partnerid,
								"prepayid": res.prepayid,
								"package": res.package,
								"noncestr": res.noncestr,
								"timestamp": res.timestamp,
								"sign": res.sign,
							}
							// var wxAppPayInfo = {
							// 	"appId": 'wx7fe0b8c7efcc7bee',
							// 	"partnerId": res.partnerid,
							// 	"prepayId": 'wx1810213084897196cc3868193691580000',
							// 	"packageValue": res.package,
							// 	"nonceStr": 'dCdFVK0iZAxVleTsDp8dQwSVwJQmuQCP',
							// 	"timeStamp": '1634523688',
							// 	"sign": 'G7/OkomJkfp8o27xXdOsG9BEtQ4Jz+ueL2MjphI+Zqkjfppd4D4z4Kv3rlfhCOZ8AvSaOHP5FiqH8MMpv1+6t4kSaLYtmpd+dXLVzImyfckMi615qQmFJ5eMKomK63Y2wIL7xiZW2Ep92WR/woIVXJ+JNCv16D+5djau/AeTNZwICacO+QLyTZ3lVk1A6ZljffsvTJYDA2yPheh909tq3riciq58v8D70x+GDrNpYde+qbsoB52yIhJ4ccxYQts6AyNUDYgb++hp47yRq+TatOsszgEaNLI77C0EI8HtyIJCMRnPGeJ6s4CbE4wjn/ukvLVIbAY5GfF1fdpcojcCHQ==',
							// }


						}

						console.log(wxAppPayInfo)
						let _this = this;
						uni.getProvider({
							service: 'payment',
							success: res1 => {
								console.log(res1);
								// console.log(res);
								// console.log(this.getPayInfo(res));
								// let weixinorder = this.getPayInfo(res);
								console.log(wxAppPayInfo);
								console.log(Constant.PayType.WECHATPAY_APP);
								uni.requestPayment({
									provider: payType == Constant.PayType.WECHATPAY_APP ?
										'wxpay' : 'alipay',
									orderInfo: payType == Constant.PayType.WECHATPAY_APP ?
										wxAppPayInfo : res,
									success: payMentSuss => {
										console.log(payMentSuss)
										_this.routeToAfterPay(true, dvyType, vipId,
											balanceId, orderNumbers, payType)
									},
									fail: (paymentFail) => {
										console.log(paymentFail)
										_this.routeToAfterPay(false, dvyType, vipId,
											balanceId, orderNumbers, payType)
									}
								})
							},
							fail: (failRes) => {
								console.log('fail')
							}
						})





						// #endif
						// #ifdef MP-WEIXIN
						console.log({
							appId: res.appid,
							timeStamp: res.timestamp,
							nonceStr: res.noncestr,
							package: res.package,
							signType: res.signtype,
							paySign: res.paysign,
						})
						wx.requestPayment({
							appId: res.appid,
							timeStamp: res.timestamp,
							nonceStr: res.noncestr,
							package: res.package,
							signType: res.signtype,
							paySign: res.paysign,
							success: e => {
								debugger
								_this.routeToAfterPay(true, dvyType, vipId, balanceId, orderNumbers,
									payType)
							},
							fail: err => {
								debugger
								_this.routeToAfterPay(false, dvyType, vipId, balanceId,
									orderNumbers, payType)
							}
						})
						// #endif
					}
				}
			},
			errCallBack: err => {
				uni.showModal({
					title: i18n.t('index.tips'),
					content: err.data,
					confirmText: i18n.t('index.confirm'),
					showCancel: false,
					success: errModSucc => {
						if (errModSucc.confirm) {
							uni.navigateTo({
								url: '/packageUser/pages/orderList/orderList?sts=0'
							})
						}
					}
				})
			}
		}
		http.request(params)
	},
	// /二次签名
	getPayInfo(orderInfo) {
		console.log(orderInfo);
		let res = orderInfo; // 后台返回的统一下单数据
		let key = ""; // 加密Key，微信支付填写的key（后台提供）
		let payInfo = {
			appid: res.appid,
			noncestr: res.noncestr,
			package: res.package,
			partnerid: res.partnerid,
			prepayid: res.prepayid,
			timestamp: Number(res.timestamp),
		};
		console.log(payInfo);
		// 键值对按照ASCII码从小到大排序生成类似：appid=xxx&body=xx&device_info=1000
		let keyValueStr = this.mapObjToKeyValue(payInfo, true);
		console.log(keyValueStr);
		// 插入加密Key到最后
		let strSignTemp = `${keyValueStr}&key=${key}`;
		// console.log(strSignTemp)
		// 真正的二次加密（需要引入md5.js源码，小编文章最后会附）
		let sign = MD5(strSignTemp).toUpperCase().substr(0, 32);
		// console.log(sign) // 可以去微信支付文档做校验
		payInfo.sign = sign;
		// 返回字符串给uniapp调起支付用
		return JSON.stringify(payInfo);
	},
	/*
	 * 根据object生成key value字符串
	 * @params obj: any 要map的对象
	 * @params isSort: boolean 是否根据ASCII字典排序
	 */
	mapObjToKeyValue(obj, isSort = false) {
		let keys = Object.keys(obj);
		let str = "";

		if (isSort) keys.sort();
		keys.forEach(key => {
			if (obj.hasOwnProperty(key)) {
				str += `${key}=${obj[key]}&`;
			}
		});
		return str.replace(/&$/, "");
	},
	/**
	 * 支付成功或失败后的统一跳转
	 * @param {Boolean} isSuccess 是否支付成功
	 * @param {Number} dvyType 配送类型
	 * @param {Number} vipId 购买会员id
	 * @param {Number} balanceId 余额充值id
	 * @param {String} orderNumbers 订单编号
	 */
	routeToAfterPay(isSuccess, dvyType, vipId, balanceId, orderNumbers, payType) {
		let url = ''
		// 购买vip 成功与否都跳转同一个链接
		if (vipId) {
			url = '/packageMemberIntegral/pages/buyVip/buyVip'
		}
		if (isSuccess) {
			// 支付成功后的跳转
			url = balanceId ? '/packageUser/pages/myWallet/myWallet' : dvyType == 2 ?
				'/packageProduct/pages/paySuccess/paySuccess?sts=1&orderNumbers=' + orderNumbers + '&dvyType=' +
				dvyType :
				'/packageProduct/pages/pay-result/pay-result?sts=1&orderNumbers=' + orderNumbers + '&payType=' + payType
		} else {
			// 支付失败的跳转
			url = balanceId ? '/packageUser/pages/rechargeBalance/rechargeBalance' :
				'/packageProduct/pages/pay-result/pay-result?sts=0&orderNumbers=' + orderNumbers + '&payType=' + payType
		}
		uni.redirectTo({
			url: url
		})
	},

	/**
	 * 唤起支付
	 * @param {Object} paydata 支付需要的参数
	 * @param {Object} cb 成功回调
	 * @param {Object} errorCb 失败回调
	 */
	toPay({
		payType,
		redirectPage,
		paydata,
		cb,
		errorCb
	}) {
		if (Constant.PayType.WECHATPAY_H5 == payType) {
			var redirectUrl = ''
			if (!redirectPage) {
				redirectUrl = window.location.href
			} else {
				var {
					protocol,
					host
				} = window.location
				redirectUrl = `${protocol}//${host}` + redirectPage
			}

			var url = encodeURIComponent(redirectUrl)
			window.location.href = paydata + "&redirect_url=" + url
		}
		// 微信公众号支付
		else if (Constant.PayType.WECHATPAY_MP == payType) {
			Wechat.callWexinPay(paydata, cb, errorCb)
		}
	},
}
